using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;

namespace RStein.Posterous.API
{
    internal static class ThreadExtensions
    {
        #region private variables
        private static Dictionary<int, SynchronizationContext> _syncContexts = new Dictionary<int, SynchronizationContext>();
        private static SynchronizationContext _defaultContext = new SynchronizationContext();

        #endregion private variables

        #region methods
        public static void SetCurrentSynchronizationContext(this Thread thread, SynchronizationContext context)
        {
            checkThreadNotNull(thread);


            _syncContexts[thread.ManagedThreadId] = context;
        }

        

        public static SynchronizationContext GetCurrentSynchronizationContext(this Thread thread)
        {
            checkThreadNotNull(thread);
            SynchronizationContext context = null;
            
            if (!_syncContexts.TryGetValue(thread.ManagedThreadId, out context))
            {
                return _defaultContext;
            }

            return context;
                        
        }

        public static void RemoveCurrentSynchronizationContext(this Thread thread)
        {
            checkThreadNotNull(thread);
            _syncContexts.Remove(thread.ManagedThreadId);
        }

        private static void checkThreadNotNull(Thread thread)
        {
            if (thread == null)
            {
                throw new ArgumentNullException("thread");
            }
        }
        #endregion methods
    
    }
}